
import java.util.Random;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.LayerManager;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author USER
 */
public class DessertCanvas extends GameCanvas implements Runnable {

    private static int JUM_RF_BIRD = 15;
    private GestureRecognizer recognizer;
    private int gesture;
    private boolean show;
    //path
    private String pathBlueBird = "";
    private String pathRedFastBird = "";
    private String pathBtnPause = "";
    private String pathBtnClose = "";
    private String pathBgDessert = "";
    private String pathBtnResume = "";
    //private String pathBgSnow = "";
    //animated sprite
    private AnimatedSprite spBlueBird;
    private AnimatedSprite[] spRedFastBird = new AnimatedSprite[JUM_RF_BIRD];
    private static int FRAME_SHADOW_WIDTH = 0;
    private static int FRAME_SHADOW_HEIGHT = 0;
    private BackgroundScroll bgScroll;
    //non animated sprite
    //private ShurikenBoxSprite spShurikenBox;
    private LayerManager lmgr;
    private boolean running = false;
    private TheBirdMIDlet midlet;
    //canvas property
    private final int CANVAS_WIDTH = getWidth();
    private final int CANVAS_HEIGHT = getHeight();
    private int bgWidth = 0;
    private int warna;
    //button
    private ButtonImage btnResume;
    private ButtonImage btnPause;
    private ButtonImage btnClose;
    private ButtonImage btnShowHighScore;
    private ButtonImage btnNextStage;
    private Image imgBtnPause;
    private Image imgBtnClose;
    private Image imgTransparent;
    private Image imgGameOver;
    private Image imgGreat;
    private Image imgShowHighScores;
    private Image imgNextStage;
    private Image imgBtnResume;
    //positions
    private int x = 0;
    private int y = 0;
    private int xBg = 0;
    private int yBg = 0;
    private int xBlueBird = 0;
    private int yBlueBird = 0;
    private int[] xRedFastBird = new int[JUM_RF_BIRD];
    private int[] yRedFastBird = new int[JUM_RF_BIRD];
    //private int yPlatform = 0;
    //speed
    private int speedGame = 50;
    private int speedBg = 5;
    //private int speedShadow = 5;
    private int speedRedFastBird = 1;
    //conditions
    private boolean isJump = false;
    private boolean isJump2 = false;
    private boolean isDown = false;
    private boolean isTickBlash = false;
    private boolean isKena = false;
    private boolean isAttack = false;
    private boolean isGameOver = false;
    private boolean isNextLevel = false;
    private boolean isPaused = false;
    //utilities game
    private int darah = 60;
    private int jarak = 0;
    private Random myRandom = new Random();
    //jumlah

    public DessertCanvas(TheBirdMIDlet midlet) {
        super(true);
        setFullScreenMode(true);

        warna = 0xb7df27;
        this.midlet = midlet;

        yBg = 0;

        FRAME_SHADOW_WIDTH = 23;
        FRAME_SHADOW_HEIGHT = 25;
        pathBlueBird = "/black-shadow320.png";
        pathRedFastBird = "/jahat-shadow320.png";
        pathBtnPause = "/pause.png";
        pathBtnClose = "/close.png";
        pathBgDessert = "/bg-dessert320.png";
        pathBtnResume = "/btnResume320.png";
        bgWidth = 640;

        xBlueBird = (int) ((CANVAS_WIDTH * 0.2));
        yBlueBird = (int) ((CANVAS_HEIGHT * 0.5));
        //yPlatform = (int) ((CANVAS_HEIGHT * 0.8));

        try {
            // nonanimated sprites
            //spShurikenBox = new ShurikenBoxSprite(Image.createImage(pathShurikenBox));

            //pilih background
            bgScroll = new BackgroundScroll(Image.createImage(pathBgDessert));
            bgScroll.setRefPixelPosition(xBg, yBg);

            //animated sprite
            spBlueBird = new AnimatedSprite(Image.createImage(pathBlueBird),
                    FRAME_SHADOW_WIDTH, FRAME_SHADOW_HEIGHT);
            spBlueBird.defineReferencePixel(FRAME_SHADOW_WIDTH / 2, FRAME_SHADOW_HEIGHT / 2);
            spBlueBird.setRefPixelPosition(xBlueBird, yBlueBird);


            lmgr = new LayerManager();

            for (int i = 0; i < JUM_RF_BIRD; i++) {
                xRedFastBird[i] = (1 + getRandomInt(CANVAS_WIDTH * 2));
                yRedFastBird[i] = (getRandomInt((int) (CANVAS_HEIGHT * 0.8)));
            }

            for (int i = 0; i < JUM_RF_BIRD; i++) {
                spRedFastBird[i] = new AnimatedSprite(Image.createImage(pathRedFastBird),
                        FRAME_SHADOW_WIDTH, FRAME_SHADOW_HEIGHT);
                spRedFastBird[i].defineReferencePixel(FRAME_SHADOW_WIDTH / 2, FRAME_SHADOW_HEIGHT / 2);
                //spRedFastBird[i].setRefPixelPosition(xRedFastBird, yRedFastBird);
                lmgr.append(spRedFastBird[i]);
            }

            for (int i = 0; i < JUM_RF_BIRD; i++) {
                spRedFastBird[i].setRefPixelPosition(xRedFastBird[i], yRedFastBird[i]);
            }

            /*
            spShuriken = new AnimatedSprite(Image.createImage(pathShuriken),
            FRAME_SHURIKEN_WIDTH, FRAME_SHURIKEN_HEIGHT);
            spShuriken.defineReferencePixel(FRAME_SHURIKEN_WIDTH / 2,
            FRAME_SHURIKEN_HEIGHT / 2);

            xShuriken1 = xShadow;
            yShuriken1 = yShadow;
            spShuriken.setRefPixelPosition(xShuriken1, yShuriken1);
             *
             */

            // create and add to layer manager

            lmgr.append(spBlueBird);
            lmgr.append(spRedFastBird[0]);
            //lmgr.append(spShurikenBox);
            //lmgr.append(spShuriken);
            lmgr.append(bgScroll);
            //spShuriken.setVisible(false);

            //button
            imgBtnPause = Image.createImage(pathBtnPause);
            imgBtnClose = Image.createImage(pathBtnClose);
            imgTransparent = Image.createImage("/transparent.png");
            imgGameOver = Image.createImage("/gameover.png");
            imgGreat = Image.createImage("/great.png");
            imgShowHighScores = Image.createImage("/btnShowHighScores.png");
            imgNextStage = Image.createImage("/btnNextStage.png");
            imgBtnResume = Image.createImage(pathBtnResume);


            int xyArea[] = new int[4];
            int wPause = 0;
            int hPause = 0;
            int wShowHighScores = CANVAS_WIDTH / 2 - imgGameOver.getWidth() / 2;
            int hShowHighScores = CANVAS_HEIGHT / 2 + imgGameOver.getHeight();

            int xResume = getWidth() / 2 - (imgBtnResume.getWidth() / 2);
            int yResume = getHeight() / 2 - (imgBtnResume.getHeight() / 2);
            xyArea[0] = xResume; //x1
            xyArea[1] = xResume + imgBtnResume.getWidth(); //x2
            xyArea[2] = yResume; //y1
            xyArea[3] = yResume + imgBtnResume.getHeight(); //y2
            btnResume = new ButtonImage("resume", imgBtnResume, imgBtnResume,
                    imgBtnResume, xResume,
                    yResume, xyArea, Graphics.TOP | Graphics.LEFT);

            int xClose = getWidth() / 2 - (imgBtnClose.getWidth() / 2) - 5;
            int yClose = getHeight() / 2 - (imgBtnClose.getHeight() / 2) - 40;
            xyArea[0] = xClose; //x1
            xyArea[1] = xClose + imgBtnClose.getWidth(); //x2
            xyArea[2] = yClose; //y1
            xyArea[3] = yResume + imgBtnClose.getHeight(); //y2
            btnClose = new ButtonImage("close", imgBtnClose, imgBtnClose,
                    imgBtnClose, xClose,
                    yClose, xyArea, Graphics.TOP | Graphics.LEFT);

            xyArea[0] = hPause; //x1
            xyArea[1] = hPause + imgBtnPause.getWidth(); //x2
            xyArea[2] = wPause; //y1
            xyArea[3] = wPause + imgBtnPause.getHeight(); //y2
            btnPause = new ButtonImage("pause", imgBtnPause, imgBtnPause,
                    imgBtnPause, wPause,
                    hPause, xyArea, Graphics.TOP | Graphics.LEFT);

            xyArea[0] = hShowHighScores; //x1
            xyArea[1] = hShowHighScores + imgShowHighScores.getWidth(); //x2
            xyArea[2] = wShowHighScores; //y1
            xyArea[3] = wShowHighScores + imgShowHighScores.getHeight(); //y2
            btnShowHighScore = new ButtonImage("showhighscores", imgShowHighScores, imgShowHighScores,
                    imgShowHighScores, wShowHighScores,
                    hShowHighScores, xyArea, Graphics.TOP | Graphics.LEFT);

            btnNextStage = new ButtonImage("nextstage", imgNextStage, imgNextStage,
                    imgNextStage, wShowHighScores,
                    hShowHighScores, xyArea, Graphics.TOP | Graphics.LEFT);


        } catch (Exception e) {
        }
    }

    //start thread
    public void start() {
        running = true;
        Thread t = new Thread(this);
        t.start();
    }

    //game loop
    public void run() {
        Graphics g = getGraphics();
        while (running) {
            // look for keypress
            if (!isGameOver && !isNextLevel) {
                checkForKeys();
                checkForCollision();
                jarak++;
                if (jarak == 500) {
                    isNextLevel = true;
                }
            }

            if (!isKena) {
                drawDisplay(g);
            } else {
                //flash backlight and vibrate device
                //midlet.display.flashBacklight(500);
                if (TheBirdMIDlet.isVibrate) {
                    midlet.display.vibrate(400);
                }
                drawDisplay(g);
                isKena = false;
                darah = darah - 2;
                if (darah < 2) {
                    isGameOver = true;
                }
            }
            try {
                Thread.sleep(speedGame);
            } catch (InterruptedException ie) {
            }
        }
    }

    protected void keyPressed(int keyCode) {
        if (keyCode == -6) {
            midlet.showMenuCanvas();
        }
    }

    private void checkForKeys() {
        int keyState = getKeyStates();

        if ((keyState & FIRE_PRESSED) != 0) {
            isAttack = true;
        }
        if ((keyState & LEFT_PRESSED) != 0) {
            //spMan.moveLeft();
            keKiri();
        }
        if ((keyState & RIGHT_PRESSED) != 0) {
            //spMan.moveRight(CANVAS_WIDTH);
            keKanan();
        }
        if ((keyState & UP_PRESSED) != 0) {
            //checkJump();
            keAtas();
        }
        if ((keyState & DOWN_PRESSED) != 0) {
            //spMan.moveDown(CANVAS_HEIGHT);
            keBawah();
        }
    }

    private void drawTransparent(Graphics g) {
        g.drawImage(imgTransparent, 0, 0, Graphics.TOP | Graphics.LEFT);
    }

    private void checkForCollision() {
        for (int i = 0; i < JUM_RF_BIRD; i++) {
            if (spBlueBird.collidesWith(spRedFastBird[i], true)) {
                isKena = true;
            }
        }
    }

    private void drawTrasparentHighScores(Graphics g) {
        drawTransparent(g);
        g.drawImage(imgGameOver, CANVAS_WIDTH / 2 - imgGameOver.getWidth() / 2,
                CANVAS_HEIGHT / 2 - imgGameOver.getHeight() / 2,
                Graphics.TOP | Graphics.LEFT);
        g.setColor(0x0000ff);
        g.drawString("Your Score : " + jarak, 150, 150, Graphics.TOP | Graphics.LEFT);
        btnShowHighScore.paint(g);
    }

    private void drawTrasparentNextStage(Graphics g) {
        drawTransparent(g);
        g.drawImage(imgGreat, CANVAS_WIDTH / 2 - imgGreat.getWidth() / 2,
                CANVAS_HEIGHT / 2 - imgGreat.getHeight() / 2,
                Graphics.TOP | Graphics.LEFT);
        btnNextStage.paint(g);
    }

    private void drawDisplay(Graphics g) {
        //setFullScreenMode(true);
        //clear background
        cobaPaint(g);

        spBlueBird.nextFrame();
        spBlueBird.setPosition(xBlueBird, yBlueBird);

        if (xBg == -bgWidth) {
            xBg = 0;
        } else {
            xBg = xBg - speedBg;
        }
        bgScroll.setPosition(xBg, yBg);

        for (int i = 0; i < JUM_RF_BIRD; i++) {
            if (xRedFastBird[i] < 0) {
                //random aggy
                xRedFastBird[i] = (1 + getRandomInt(CANVAS_WIDTH * 2));
                yRedFastBird[i] = (getRandomInt((int) (CANVAS_HEIGHT)));

                if (xRedFastBird[i] < (CANVAS_WIDTH + 50)) {
                    xRedFastBird[i] = CANVAS_WIDTH + 100;
                }
            } else {
                xRedFastBird[i] = xRedFastBird[i] - speedRedFastBird;
            }
            spRedFastBird[i].setPosition(xRedFastBird[i], yRedFastBird[i]);
            spRedFastBird[i].nextFrame();
        }

        //paint all layers
        lmgr.paint(g, 0, 0);
        btnPause.paint(g);

        /* dara*/
        g.setColor(0xff0000);
        g.fillRect(172, 5, 62, 10);
        g.setColor(0xffffff);
        g.fillRect(173, 6, 60, 8);
        g.setColor(0xff0000);
        g.fillRect(173, 6, darah, 8);

        g.setColor(0x0000ff);

        g.setFont(MenuCanvas.SMALL_BOLD_FONT);
        g.drawString(formatJarak(jarak), 120, 3, Graphics.TOP | Graphics.LEFT);
        //System.out.println(formatJarak(jarak));

        if (isGameOver) {
            drawTrasparentHighScores(g);
        }
        if (isNextLevel) {
            drawTrasparentNextStage(g);
        }

        //flush off-screen buffer to display
        flushGraphics();
    }

    private void cobaPaint(Graphics g) {
        if (show) {
            g.setColor(0xffff00);
            String s;
            boolean drawTap = false;
            boolean drawArea = false;

            switch (gesture) {
                case GestureRecognizer.TAP:
                    s = "tap";
                    drawTap = true;
                    break;
                case GestureRecognizer.TAP_N_HOLD:
                    s = "tap'n'hold";
                    drawTap = true;
                    break;
                case GestureRecognizer.DRAG_UP:
                    s = "drag up";
                    //System.out.println(s);
                    keAtas();
                    break;
                case GestureRecognizer.DRAG_DOWN:
                    s = "drag down";
                    //System.out.println(s);
                    keBawah();
                    break;
                case GestureRecognizer.DRAG_LEFT:
                    s = "drag left";
                    //System.out.println(s);
                    keKiri();
                    break;
                case GestureRecognizer.DRAG_RIGHT:
                    s = "drag right";
                    //System.out.println(s);
                    keKanan();
                    break;
                case GestureRecognizer.CIRCLE_CLOCK:
                    s = "circle clockwise";
                    drawArea = true;
                    break;
                case GestureRecognizer.CIRCLE_ANTI:
                    s = "circle anti-clockwise";
                    drawArea = true;
                    break;
                default:
                    s = "unknown";
                    break;
            }

            g.drawString(s, getWidth() / 2, getHeight(), Graphics.HCENTER | Graphics.BOTTOM);

            if (drawTap) {
                g.drawRect(recognizer.getTapX() - 4, recognizer.getTapY() - 4, 8, 8);
            }
            if (drawArea) {
                g.drawRect(recognizer.getAreaX(), recognizer.getAreaY(), recognizer.getAreaWidth(), recognizer.getAreaHeight());
            }
        }
    }

    private void keAtas() {
        if (yBlueBird > 15) {
            yBlueBird = yBlueBird - 5;
        }
    }

    private void keBawah() {
        if (yBlueBird < getHeight() - 45) {
            yBlueBird = yBlueBird + 5;
        }
    }

    private void keKiri() {
        if (xBlueBird > 5) {
            xBlueBird = xBlueBird - 5;
        }
    }

    private void keKanan() {
        if (xBlueBird < getWidth() - 25) {
            xBlueBird = xBlueBird + 5;
        }
    }

    public void stop() {
        running = false;
    }

    protected void pointerPressed(int x, int y) {
        if (isPaused) {
        } else {
            recognizer = new GestureRecognizer(x, y);
            show = false;
            repaint();

            this.x = x;
            this.y = y;
            if (!isGameOver && !isNextLevel) {
                if (x > btnPause.xImage
                        && x < (btnPause.xImage + btnPause.imageWidth)
                        && y > btnPause.yImage
                        && y < (btnPause.yImage + btnPause.imageHeight)) {
                    btnPause.pointerPressed(x, y);
                    //System.out.println("pause coy!");
                    paused();
                    showNotify();
                    repaint();
                }
            }

            if (isGameOver) {
                if (x > btnShowHighScore.xImage
                        && x < (btnShowHighScore.xImage + btnShowHighScore.imageWidth)
                        && y > btnShowHighScore.yImage
                        && y < (btnShowHighScore.yImage + btnShowHighScore.imageHeight)) {
                    btnShowHighScore.pointerPressed(x, y);
                    midlet.showHighScores(jarak + darah, true);
                    repaint();
                }
            }

            if (isNextLevel) {
                if (x > btnNextStage.xImage
                        && x < (btnNextStage.xImage + btnNextStage.imageWidth)
                        && y > btnNextStage.yImage
                        && y < (btnNextStage.yImage + btnNextStage.imageHeight)) {
                    btnNextStage.pointerPressed(x, y);
                    midlet.showSnowCanvas();
                    repaint();
                }
            }
        }
    }

    protected void pointerDragged(int x, int y) {
        if (isPaused) {
        } else {
            recognizer.addMotion(x, y);
        }


    }

    protected void pointerReleased(int x, int y) {
        if (isPaused) {
            if (x > btnResume.xImage
                    && x < (btnResume.xImage + btnResume.imageWidth)
                    && y > btnResume.yImage
                    && y < (btnResume.yImage + btnResume.imageHeight)) {
                isPaused = false;
                start();
                repaint();
            }
            if (x > btnClose.xImage
                    && x < (btnClose.xImage + btnClose.imageWidth)
                    && y > btnClose.yImage
                    && y < (btnClose.yImage + btnClose.imageHeight)) {
                midlet.showMenuCanvas();
            }
        } else {
            recognizer.endGesture(x, y);
            gesture = recognizer.getGesture();

            if (!isGameOver && !isNextLevel) {
                show = true;
            }
            repaint();

            this.x = x;
            this.y = y;
        }


    }

    private String formatJarak(long i) {
        String s = "";
        if (i < 10) {
            s = "000" + String.valueOf(i);
        } else if (i < 100) {
            s = "00" + String.valueOf(i);
        } else if (i < 1000) {
            s = "0" + String.valueOf(i);
        } else {
            s = String.valueOf(i);
        }

        s = s + " m";
        return s;
    }

    private int getRandomInt(int upper) {
        int retVal = myRandom.nextInt() % upper;
        if (retVal < 0) {
            retVal += upper;
        }
        return (retVal);
    }

    protected void hideNotify() {
        //super.hideNotify();
        //hideNotify();
        paused();
        int xResume = getWidth() / 2 - (imgBtnResume.getWidth() / 2);
        int yResume = getHeight() / 2 - (imgBtnResume.getHeight() / 2);

        btnResume.setPositionXY(xResume, yResume,
                Graphics.TOP | Graphics.LEFT);
    }

    protected void showNotify() {
        //super.showNotify();
        //showNotify();

        if (isPaused) {
            Graphics g = getGraphics();
            drawTransparent(g);
            btnClose.paint(g);
            btnResume.paint(g);
        }

    }

    private void paused() {
        isPaused = true;
        running = false;
    }
}
